<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>录音功能示例</title>
</head>

<body>
    <h1>录音功能示例</h1>
    <button id="start-recording">开始录音</button>
    <button id="stop-recording" disabled>停止录音</button>
    <audio id="audio-preview" controls></audio>
</body>
<script>
    let mediaRecorder; // 用于控制录音的MediaRecorder对象
    let audioChunks = []; // 用于存储录音数据的数组
    let audioBlob; // 最终的音频文件

    // 获取按钮和音频播放器
    const startButton = document.getElementById('start-recording');
    const stopButton = document.getElementById('stop-recording');
    const audioPreview = document.getElementById('audio-preview');

    // 开始录音
    startButton.addEventListener('click', async () => {
        try {
            // 请求录音权限
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            mediaRecorder = new MediaRecorder(stream);

            // 监听录音数据
            mediaRecorder.ondataavailable = (event) => {
                if (event.data.size > 0) {
                    audioChunks.push(event.data);
                }
            };

            // 开始录音
            mediaRecorder.start();
            console.log('录音已开始');
            startButton.disabled = true;
            stopButton.disabled = false;
        } catch (error) {
            console.error('录音权限获取失败：', error);
            alert('录音权限获取失败，请检查浏览器设置或使用HTTPS环境');
        }
    });

    // 停止录音
    stopButton.addEventListener('click', () => {
        mediaRecorder.stop();
        console.log('录音已停止');
        startButton.disabled = false;
        stopButton.disabled = true;
    });

    // 处理录音结束
    mediaRecorder.onstop = () => {
        audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
        audioChunks = []; // 清空录音数据

        // 创建音频URL并播放
        const audioURL = URL.createObjectURL(audioBlob);
        audioPreview.src = audioURL;
        console.log('音频已生成，可以播放');
    };
</script>

</html>